package cn.wzg.fragmentbase;

import android.os.Bundle;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class DynamicLoadActivity extends AppCompatActivity {
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    private Fragment fragment1;
    private Fragment fragment2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_dynamic_load);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        /**
         * 动态加载：
         *  1.在布局中添加一个容器，一般使用FrameLayout
         *  2.运行时通过FragmentTransaction加载Fragment
         */
        //获得FragmentManager对象
        fragmentManager = getSupportFragmentManager();
        //开启事务，获得FragmentTransaction对象
        transaction = fragmentManager.beginTransaction();
        //创建需要添加的Fragment
        fragment1 = new LeftFragment();
        fragment2 = new RightFragment();
        //向容器内添加或替换碎片，默认情况下为LeftFragment
        transaction.replace(R.id.content,fragment1);
        //提交事务
        transaction.commit();
    }
    public void loadFragment(View view){
        transaction=fragmentManager.beginTransaction();
        int id=view.getId();
        if(id==R.id.button4){
            transaction.replace(R.id.content,fragment1);
        }else if(id==R.id.button5){
            transaction.replace(R.id.content,fragment2);
        }
        transaction.commit();
    }
}